<template>
    <div class="front-padding initialize" element-loading-text="数据加载中..." element-loading-background="#fff" v-loading.fullscreen.lock="fullLoading[0]">
        <div class="widgets bg-white">
            <div class="btn-group right">
                <el-button type="info" @click="refInitialize">刷新</el-button>
                <el-button type="primary" v-if="radioState == 1" disabled>保存</el-button>
                <el-button type="primary" v-else @click="saveInitialia">保存</el-button>
                <el-button type="primary" @click="balanceBtn">平衡</el-button>
                <el-button type="success" @click="subsidiaryLedger($store.state.initializeVal[0])">明细账</el-button>
                <el-button-group class="btn-other">
                    <el-button title="导出" @click="exportExcel">
                        <img src="../../../assets/images/export.png" alt="">
                    </el-button>
                    <el-button title="打印">
                        <img src="../../../assets/images/print.png" alt="">
                    </el-button>
                    <el-button title="帮助">
                        <img src="../../../assets/images/help.png" alt="">
                    </el-button>
                </el-button-group>
            </div>
        </div>
        <div class="table bg-white bj">
            <el-scrollbar style="height: 100%;">
                <tree-table :data="data" :columns="columns" class="tb-edit" highlight-current-row>
                    <el-table-column prop="name" label="名称" align="center"></el-table-column>
                    <el-table-column prop="isJie" label="借/贷" width="60" align="center">
                        <template slot-scope="scope">
                            <span v-if="(scope.row.code.split('.')[0].length != 5 && scope.row.balanceDirection == 0) && (scope.row.code.split('.')[0].length != 3 && scope.row.balanceDirection == 0)">借</span>
                            <span v-if="(scope.row.code.split('.')[0].length != 5 && scope.row.balanceDirection == 1) && (scope.row.code.split('.')[0].length != 3 && scope.row.balanceDirection == 1)">贷</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="money" label="金额" align="center">
                        <template slot-scope="scope">
                            <div v-if="scope.row.name == '会计科目'">
                                <span></span>
                            </div>
                            <div v-else-if="radioState == 1">
                                <span>{{currency(scope.row.money)}}</span>
                            </div>
                            <div v-else-if="scope.row.betweenObject === 1">
                                <span>{{currency(scope.row.money)}}</span>
                            </div>
                            <div v-else-if="scope.row.subAssertList.length === 0 && scope.row.betweenObject === 0">
                                <el-input size="small" type="number" @focus="focus($event)" v-model="scope.row.money" placeholder="请输入金额" @change="handleEdit(scope.$index, scope.row)"></el-input> 
                                <span>{{currency(scope.row.money)}}</span>
                            </div>
                            <div v-else>
                                <span>{{currency(scope.row.money)}}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="betweenObject" label="明细账" width="80" align="center">
                        <template slot-scope="scope">
                            <div v-if="scope.row.betweenObject === 0">
                                <el-checkbox disabled></el-checkbox>
                            </div>
                            <div v-else>
                                <el-checkbox checked disabled></el-checkbox>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" align="center">
                        <template slot-scope="scope">
                            <div v-if="radioState == 1">
                                <span>{{scope.row.remark}}</span>
                            </div>
                            <div v-else>
                                <el-input size="small" type="text" @focus="focus($event)" v-model="scope.row.remark" placeholder="请输入备注"></el-input>
                                <span>{{scope.row.remark}}</span>
                            </div>
                        </template>
                    </el-table-column>
                </tree-table>
            </el-scrollbar>
        </div>
    </div>
</template>
<script>
    /**
     * Author: 赵巧芬
     * Date: 2019-3
     * Description: 初始化组件
    */
    import treeTable from '@/components/treeTable'
    export default {
        components: {
            treeTable
        },
        data() {
            return {
                fullLoading: this.$store.state.initializeStore.fullLoading,
                searchText: '',                     //搜索文本
                multipleSelection: [],              //选中的行数据集合
                columns: [                          //表格数据===编码
                    {
                        text: '编码',
                        value: 'code',
                    }
                ],              
                data:this.$store.state.initializeStore.treeData,//表格数据
                dataList: [],                       //树形表格list数据
                searchAllResult: this.$store.state.initializeStore.searchAllResult,//搜索结果
                radioState: '',                     //启用系统状态
                systemId: this.$store.state.systemId,
                accountantData: '',//金额文本框改变打印出会计科目的数据
                assetsData: [],//金额文本框改变时资产数据
                oneMoney: '',//借
                twoMoney: '',//贷
                assetsSumData: [],//资产数据
                liabilitySumData: [],//负债数据
                equitySumData: [],//权益数据
                isSave: this.$store.state.initializeStore.isSave,//明细账金额改变的状态
            }
        },
        watch: {
            searchText(newVal) {
                if(!newVal) {
                    this.data = this.$store.state.initializeStore.treeData;
                }
            },
            isSave(newVal){
                if(newVal[0]){
                    this.saveInitialia();
                }
            }
        },
        computed: {
            // subSidiaryState(){
            //     return this.subSidiaryState;
            // }
        },
        methods: {
            currency(moneyA){                       //过滤金额
                if (moneyA && moneyA != null) {
                    moneyA = String(moneyA);
                    var left = moneyA.split('.')[0], right = moneyA.split('.')[1];
                    right = right ? (right.length >= 2 ? '.' + right.substr(0, 2) : '.' + right + '0') : '.00';
                    var temp = left.split('').reverse().join('').match(/(\d{1,3})/g);
                    return (Number(moneyA) < 0 ? '-' : '') + temp.join(',').split('').reverse().join('') + right;
                    } else if (moneyA === 0) { // 注意===在这里的使用，如果传入的moneyA为0,if中会将其判定为boolean类型，故而要另外做===判断
                    return '0.00';
                    } else {
                    return '';
                }
            },
            subsidiaryLedger(obj){                     //明细账
                if(obj && obj['name']){
                    if(this.$store.state.initializeVal.length > 0) {
                        if(this.$store.state.initializeVal.length < 2){
                            if(this.$store.state.initializeVal[0]['betweenObject'] == 1){
                                if(obj['name'] == '银行存款'){
                                    this.$util.openLayerIframe({title: obj['name'] + '明细账', zIndex: 13, width: '60%', height: '85%', url: this.$domain + '/#/initialize/subsidiaryLedger1'});
                                }else if(obj['name'] == '应收账款' || obj['name'] == '应收票据' || obj['name'] == '预收账款'){
                                    this.$util.openLayerIframe({title: obj['name'] + '明细账', zIndex: 13, width: '60%', height: '85%', url: this.$domain + '/#/initialize/subsidiaryLedger2'});
                                }else if(obj['name'] == '应付账款' || obj['name'] == '应付票据' || obj['name'] == '预付账款'){
                                    this.$util.openLayerIframe({title: obj['name'] + '明细账', zIndex: 13, width: '60%', height: '85%', url: this.$domain + '/#/initialize/subsidiaryLedger3'});
                                }else{
                                    this.$util.openLayerIframe({title: obj['name'] + '明细账', zIndex: 13, width: '60%', height: '85%', url: this.$domain + '/#/initialize/subsidiaryLedger4'});
                                }
                            }else{
                                this.$message({message: '该数据没有明细账', type: 'warning'});
                            }
                        } else {
                            this.$message({message: '请选择单条数据', type: 'warning'});
                        }
                    } else {
                        this.$message({message: '请选择有明细账的数据', type: 'warning'});
                    }
                } else {
                    this.$message({message: '请选择有明细账的数据', type: 'warning'});
                }
            },
            handleEdit(index, row) {                //金额文本框改变触发
                row.parent.money = 0;
                this.$store.commit('initializeStore/updateHandleEdit', row);
                this.rowName(row);
            },
            rowName(row){
                if(row['parent']['name'] == '资产'){
                    this.computAssetsSum(this.$store.state.initializeStore.handleEditData);
                }else if(row['parent']['name'] == '负债'){
                    this.computedSum(this.$store.state.initializeStore.handleEditData);
                }else if(row['parent']['name'] == '共同'){
                    this.computedSum(this.$store.state.initializeStore.handleEditData);
                }else if(row['parent']['name'] == '权益'){
                    this.computedSum(this.$store.state.initializeStore.handleEditData);
                }else if(row['parent']['name'] == '成本'){
                    this.computedSum(this.$store.state.initializeStore.handleEditData);
                }else if(row['parent']['name'] == '损益'){
                    this.computedSum(this.$store.state.initializeStore.handleEditData);
                }else if(row['parent']['name'] == '表外'){
                    this.computedSum(this.$store.state.initializeStore.handleEditData);
                }else{
                    this.rowName(row['parent'])
                }
            },
            computAssetsSum(parent) {                   //合计资产总金额
                let parentArr = parent.subAssertList;
                if(parentArr.length > 0) {
                    this.oneMoney = '';//借
                    this.twoMoney = '';//贷
                    for(let i = 0; i < parentArr.length; i++) {
                        if(parentArr[i]['balanceDirection'] == 0 && parentArr[i]['money']){
                            this.oneMoney = parseFloat(Number(this.oneMoney) + Number(parentArr[i]['money']));
                        }
                        if(parentArr[i]['balanceDirection'] == 1 && parentArr[i]['money']){
                            this.twoMoney = parseFloat(Number(this.twoMoney) + Number(parentArr[i]['money']));
                        }
                        parent['money'] = parseFloat(this.oneMoney - this.twoMoney);
                    }
                }
                if(parent.parent && parent.parent.subAssertList.length > 0) {
                    parent.parent.money = 0;
                    this.computAssetsSum(parent.parent);
                }
            },
            computedSum(parent) {                   //合计其他总金额
                let parentArr = parent.subAssertList;
                if(parentArr.length > 0) {
                    for(let i = 0; i < parentArr.length; i++) {
                        if(parentArr[i]['money']) {
                            parent.money += parseFloat(parentArr[i]['money']);
                        }
                    }
                }
                if(parent.parent && parent.parent.subAssertList.length > 0) {
                    parent.parent.money = 0;
                    this.computedSum(parent.parent);
                }
            },
            focus(event) {                          //得到焦点选中
                event.currentTarget.select();
            },
            balanceBtn(){                           //平衡
                //负债+权益=负债类科目“贷方”金额之和+权益类科目“贷方”金额之和；
                this.assetsSumData = [];
                this.liabilitySumData = [];
                this.equitySumData = [];
                if(this.data){
                    for(let i = 0;i < this.data.length;i++){
                        if(this.data[i]['subAssertList'].length > 0){
                            for(let j = 0;j < this.data[i]['subAssertList'].length;j++){
                                if(this.data[i]['subAssertList'][j]['name'] == '资产'){
                                    this.assetsSumData.push(this.data[i]['subAssertList'][j]);
                                }else if(this.data[i]['subAssertList'][j]['name'] == '负债'){
                                    this.liabilitySumData.push(this.data[i]['subAssertList'][j]);
                                }else if(this.data[i]['subAssertList'][j]['name'] == '权益'){
                                    this.equitySumData.push(this.data[i]['subAssertList'][j]);
                                }
                            }
                        }
                    }
                }
                this.$store.commit('initializeStore/setAssetNum',this.currency(this.assetsSumData[0]['money']));//资产总金额
                this.$store.commit('initializeStore/setLiabilities',this.currency(this.liabilitySumData[0]['money'] + this.equitySumData[0]['money']));//负债+权益总金额
                this.$store.commit('initializeStore/setDifference',this.currency(this.assetsSumData[0]['money'] - (this.liabilitySumData[0]['money'] + this.equitySumData[0]['money'])));//差额
                let that = this;
                parent.layer.open({
                    type: 2,
                    title: '试算平衡',
                    shade: 0.3,
                    shadeClose: true,
                    zIndex: 13,
                    maxmin: true,
                    anim: 0,
                    fixed: true,
                    area: ['550px', '300px'],
                    content: this.$domain + '/#/initialize/balance',
                    success: function() {
                        $(':focus').blur();
                    },
                    end: function() {
                        that.$store.commit('initializeStore/clearSum')
                    }
                });
            },
            dataLists(arrs){                        //将树形表格数据转换成list格式
                if(arrs.length > 0) {
                    arrs.forEach(item => {
                        if(!item['money']) item['money'] = null;
                        this.dataList.push({id: item['id'],code: item['code'],name: item['name'],mnemonicCode: item['mnemonicCode'],type: item['type'],balanceDirection: item['balanceDirection'],foreignCurrencyCheck: item['foreignCurrencyCheck'],betweenObject: item['betweenObject'],journal: item['journal'],betweenObjectList: item['betweenObjectList'],locks: item['locks'],money: item['money'],remark: item['remark'],isGroup: item['isGroup']});
                        let subAssertList = item['subAssertList'];
                        if(subAssertList && subAssertList.length > 0) {
                            this.dataLists(subAssertList)
                        }
                    });
                }
            },
            saveInitialia(){                        //保存
                this.dataList = [];
                this.dataLists(this.data);
                var type = {
                    headers: {
                        'Content-type': 'application/json;charset=UTF-8'
                    }
                }
                this.$http.post(this.$url + 'subjectGroup/saveSubject', JSON.stringify(this.dataList), type).then(res => {
                    if(res.data.code == 20001){
                        this.$message({message: '保存成功', type: 'success'});
                        setTimeout(() => {
                            this.$store.dispatch('initializeStore/getTreeData', this.$url + 'subjectGroup/selectUnion?systemId=' + this.systemId);
                            this.$store.commit('clearInitializeVal');
                            this.$store.commit('initializeStore/clearInitializeVal')
                        });
                    }
                });
            },
            refInitialize(){                        //刷新
                const loading = this.$loading({
                    lock: true,
                    text: '数据刷新中...',
                    spinner: 'el-icon-loading',
                    background: '#fff'
                });
                setTimeout(() => {
                    loading.close();
                }, 1000);
            },
            exportExcel(){                          //导出
                if(this.$store.state.initializeVal.length > 0) {
                    var idSting = this.$store.state.initailizeId.join(',');           //将[1,2,3]格式转为 "1,2,3"
                    this.$http.get(this.$url + 'subjectGroup/initExport',{params: { list: idSting }}).then(res => {
                        this.$message({message: '导出成功', type: 'success'});
                        window.location.href = this.$url + 'subjectGroup/initExport?list=' + idSting;          //导出时触发
                    }).catch(err => {
                        this.$message.error(err);
                    })
                } else {
                    this.$message({message: '选择你要导出的数据', type: 'warning', duration: 2000});
                }
            },
            search(){                               //搜索
                if(this.searchText) {
                    let newArr = [],
                        dataArr = this.searchAllResult,
                        searchText = this.searchText;
                    let reg = new RegExp(this.searchText, "g");
                    dataArr.forEach(item => {
                        if(reg.test(item['remark']) || reg.test(item['money']) || reg.test(item['code']) || reg.test(item['balanceDirectionName']) || reg.test(item['name']) || (item['toPinYinName'] && reg.test(item['toPinYinName'])) || (item['toPinYinBalanceDirectionName'] && reg.test(item['toPinYinBalanceDirectionName']))) {
                            newArr.push(item);
                        }
                    });
                    // this.data = newArr;
                }
            }
        },
        mounted() {
            this.$store.dispatch('initializeStore/getTreeData', this.$url + 'subjectGroup/selectUnion?systemId=' + this.systemId);//获取初始化树形表格数据
            this.$store.dispatch('initializeStore/getSearchData', this.$url + 'subjectGroup/likeName');//获取拼音搜索的总数据
            this.$store.dispatch('initializeStore/getCompactData', this.$url + 'auxiliary/select');//辅助资料树形所有数据
            //判断启用系统是否是结束初始化
            let enableStatus = Number(localStorage.getItem('setRadio'));
            enableStatus ? this.radioState = enableStatus : this.radioState = 0;
        }
    }
</script>
<style scoped>
    .table {height: calc(100% - 54px);}
</style>

<style lang='less'>
    .initialize{
        .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner {
            background-color: #409EFF !important;border-color: #409EFF !important;
        }
        .el-checkbox__input.is-disabled.is-checked .el-checkbox__inner::after{
            border-color: #fff !important;
        }
        .tb-edit .el-input {
            display: none
        }
        .tb-edit .current-row .el-input {
            display: block
        }
        .tb-edit .current-row .el-input+span {
            display: none
        }
        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
        }
        input[type="number"] {
            -moz-appearance: textfield;
        }
    }
</style>